package org.embedchat.protocol.codec.client;

import org.embedchat.protocol.Constants;
import org.embedchat.protocol.codec.AbstractMessageDecoder;
import org.embedchat.protocol.message.AbstractMessage;
import org.embedchat.protocol.message.client.LoginMessage;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import java.io.DataInputStream;
import java.io.IOException;

public class LoginMessageDecoder extends AbstractMessageDecoder {
	
    public LoginMessageDecoder() {
        super(Constants.LOGIN_MESSAGE);
    }

    protected AbstractMessage decodeBody(IoSession session, ByteBuffer in, long bodyLength) {
        if (in.remaining() < bodyLength) {
            return null;
        }
        LoginMessage m = new LoginMessage();
        DataInputStream is = null;
        try {
            is = new DataInputStream(in.asInputStream());
            m.setRoomId(is.readInt());
            m.setLogin(is.readUTF());
            m.setPassword(is.readUTF());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return m;
    }

	public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1) throws Exception {
	}
}
